﻿using System;
using System.IO;
using AppCommon;
using Controller;
using Model;

public partial class admincenter_EditPost : System.Web.UI.Page
{
    public static string _idPost = "";
    public static User _user;
    public static Post _post;
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {            
            if (Session[Constants.S_ADMIN_USER] != null)
            {
                // Ok
                _user = (User) Session[Constants.S_ADMIN_USER];
            }
            else
            {
                Response.Redirect("~/admincenter/");
            }
            BindDatatoDDL.BindCategory(ddlCategory);
            string idPost = Request.QueryString["Id"];
            if (idPost != null)
            {
                _idPost = idPost;
                BindData(idPost);
            }
            else
            {
                Response.Redirect("~/admincenter/Error.aspx");
            }
        }
    }

    public void BindData(string idPost)
    {
        var postController = new PostController();
        var post = postController.FindPostById(idPost);

        if (post.Count > 0)
        {
            tbId.Text = post[0].Id;
            tbTieude.Text = post[0].Title;
            ddlCategory.SelectedValue = post[0].IdCategory;
            tbMota.Text = post[0].Description;
            ckeditor1.Text = Server.HtmlDecode(post[0].Content);
            tbNguon.Text = post[0].Source;
            tbLinkDown.Text = post[0].LinkDownLoad;
            tbTags.Text = post[0].Tags;
            cbTrangThai.Checked = Convert.ToBoolean(post[0].Status);
            tbPhanhoi.Text = post[0].FeedBack;

            _post = post[0];
        }
        else
        {
            Response.Redirect("~/admincenter/Error.aspx");
        }
    }

    protected void btnHuy_OnClick(object sender, EventArgs e)
    {
        Response.Redirect("~/admincenter/PostsManager.aspx");
    }

    protected void btnCapnhat_OnClick(object sender, EventArgs e)
    {
        var post = new Post();
        var postController = new PostController();
        try
        {
            post.Id = tbId.Text;
            post.Title = tbTieude.Text;
            post.IdUser = _user.Id;
            post.UniqueId = Common.ConvertToUnSign(tbTieude.Text);
            post.IdCategory = Request.Form[ddlCategory.UniqueID];
            post.Description = tbMota.Text;
            post.Content = Server.HtmlEncode(ckeditor1.Text);
            if (fuAnhbia.HasFile)
            {
                var pathAnhbia = Server.MapPath(Constants.UPLOAD_IPost);
                if (!Directory.Exists(pathAnhbia))
                {
                    Directory.CreateDirectory(pathAnhbia);
                }
                // validate file image
                string[] validFileTypes = { "gif", "png", "jpg", "jpeg" };
                var extFile = Path.GetExtension(fuAnhbia.PostedFile.FileName);
                var isValidate = false;

                if (extFile != null)
                {
                    foreach (var type in validFileTypes)
                    {
                        if (extFile.Equals("." + type))
                        {
                            isValidate = true;
                            break;
                        }
                    }
                }

                if (!isValidate)
                {
                    lbValidateAb.ForeColor = System.Drawing.Color.Red;
                    lbValidateAb.Text = "Invalid file with extension!";
                    post.ImagePanorama = Constants.NO_IMAGE;
                }
                else
                {
                    lbValidateAb.ForeColor = System.Drawing.Color.Green;
                    lbValidateAb.Text = "Ok!";
                    // Luu file 
                    fuAnhbia.SaveAs(pathAnhbia + tbId.Text + "_pan_" + DateTime.Now.ToString("ddMMyyhhmmss") +
                                    extFile);
                    post.ImagePanorama = tbId.Text + "_pan_" + DateTime.Now.ToString("ddMMyyhhmmss") + extFile;
                }
            }
            else
            {
                post.ImagePanorama = _post.ImagePanorama;
            }
            if (fuAnhDaidien.HasFile)
            {
                var pathAnhbia = Server.MapPath(Constants.UPLOAD_IPost);
                if (!Directory.Exists(pathAnhbia))
                {
                    Directory.CreateDirectory(pathAnhbia);
                }
                // validate file image
                string[] validFileTypes = { "gif", "png", "jpg", "jpeg" };
                var extFile = Path.GetExtension(fuAnhDaidien.PostedFile.FileName);
                var isValidate = false;

                if (extFile != null)
                {
                    foreach (var type in validFileTypes)
                    {
                        if (extFile.Equals("." + type))
                        {
                            isValidate = true;
                            break;
                        }
                    }
                }

                if (!isValidate)
                {
                    lbValidateTb.ForeColor = System.Drawing.Color.Red;
                    lbValidateTb.Text = "Invalid file with extension!";
                    post.ImageThumbnail = Constants.NO_IMAGE;
                }
                else
                {
                    lbValidateTb.ForeColor = System.Drawing.Color.Green;
                    lbValidateTb.Text = "Ok!";
                    // Luu file 
                    fuAnhDaidien.SaveAs(pathAnhbia + tbId.Text + "_thum_" + DateTime.Now.ToString("ddMMyyhhmmss") +
                                    extFile);
                    post.ImageThumbnail = tbId.Text + "_thum_" + DateTime.Now.ToString("ddMMyyhhmmss") + extFile;
                }
            }
            else
            {
                post.ImageThumbnail = _post.ImageThumbnail;
            }

            post.Source = tbNguon.Text;
            post.LinkDownLoad = tbLinkDown.Text;
            post.Tags = tbTags.Text;
            post.Status = Convert.ToInt32(cbTrangThai.Checked);
            post.LastDateUpdated = DateTime.Now;
            post.LastUpdatedBy = _user.UserName;
            // Goi phuong thuc cap nhat post
            var intResult = postController.EditPost(post);
            if (intResult > 0)
            {
                litResult.Text = "<p class=\"alert alert-success\">Cập nhật dữ liệu thành công.</p>";
            }
            else
            {
                litResult.Text = "<p class=\"alert alert-danger\">Cập nhật dữ liệu thất bại! Xảy ra lỗi trong quá trình cập nhật.</p>";
            }
        }
        catch (Exception)
        {
            litResult.Text = "<p class=\"alert alert-danger\">Cập nhật dữ liệu thất bại! Xảy ra lỗi trong quá trình cập nhật.</p>";
            throw;
        }
    }
}